//
//  SettingViewController.m
//  location
//
//  Created by Dongxiang Xu on 2025/5/29.
//

#import "SettingViewController.h"
#import "LoginViewController.h"
#import "BlingPhoneView.h"
#import "UIImageView+WebCache.h"
#import "AccountLogoutView.h"
#import "UpdateUserNameView.h"
#import "UIImagePickerController+ST.h"
#import "HQImageEditViewController.h"
#import "XDXLocationManager.h"
#import "WXApi.h"
#import <AuthenticationServices/AuthenticationServices.h>

@interface SettingViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate,HQImageEditViewControllerDelegate,ASAuthorizationControllerDelegate>

@property (nonatomic,strong) UIImageView *head;

@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = LightBGColor;
    [self initView];
    [self getUserInfo];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WXBling:) name:Noti_WXBling object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)initView
{
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(16, NAVHEIGHT+6, SCREEN_WIDTH-32, 32)];
    title.font = REAL_MEDIUM_FONT(24);
    title.text = @"账号与安全";
    title.textColor = RealBlackColor;
    [self.view addSubview:title];
    
    NSArray *infoArray = @[@{@"title":@"头像"},@{@"title":@"姓名"},@{@"title":@"性别"}];
    
    UIView *infoView = [[UIView alloc] initWithFrame:CGRectMake(16, title.maxY+16, SCREEN_WIDTH-32, 162)];
    infoView.backgroundColor = RealWhiteColor;
    infoView.layer.masksToBounds = YES;
    [infoView.layer setCornerRadius:16];
    [self.view addSubview:infoView];
    
    _head = [[UIImageView alloc] initWithFrame:CGRectMake(infoView.width-76, 12, 42, 42)];
    _head.layer.masksToBounds = YES;
    [_head.layer setCornerRadius:16];
    _head.backgroundColor = GraryLightColor;
    [infoView addSubview:_head];
    
    CGFloat y = 0;
    for (int i = 0; i < infoArray.count; i ++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, y, infoView.width, i==0?66:48)];
        [infoView addSubview:button];
        y = button.maxY;
        
        UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(16, y, infoView.width-32, 1)];
        line.image = [UIImage imageNamed:@"line"];
        [infoView addSubview:line];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, 34, button.height)];
        label.textColor = RealBlackColor;
        label.font = MEDIUM_FONT(15);
        label.text = infoArray[i][@"title"];
        [button addSubview:label];
        
        UILabel *subLabel = [[UILabel alloc] initWithFrame:CGRectMake(infoView.width-134, 0, 100, button.height)];
        subLabel.textColor = GraryTooHeavyColor;
        subLabel.font = DEFAULT_FONT(14);
        subLabel.textAlignment = NSTextAlignmentRight;
        subLabel.tag = 50+i;
        [button addSubview:subLabel];
        
        UIImageView *arrow = [[UIImageView alloc] initWithFrame:CGRectMake(button.width-28, (button.height-12)/2, 12, 12)];
        arrow.image = [UIImage imageNamed:@"arrow_right"];
        [button addSubview:arrow];
        
        [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if (i==0) {
                [self album];
            }else if (i==1){
                UpdateUserNameView *view = [[UpdateUserNameView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
                [self.view addSubview:view];
                view.UpdateUserNameBlock = ^(NSString *name) {
                    subLabel.text = name;
                    
                    NSDictionary *param = [NSMutableDictionary dictionary];
                    [param setValue:[XDXShareInstance shareInstance].userId forKey:@"userId"];
                    [param setValue:name forKey:@"nickName"];
                    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                    [manager encryptedPUT:@"/system/user/modify"
                    parameters:param
                    success:^(NSDictionary *responseObject) {
                        if ([responseObject[@"code"] integerValue]==200) {
                            [[NSNotificationCenter defaultCenter] postNotificationName:Noti_ReloadNickName object:nil];
                        }else{
                            [[HCToast shareInstance] showToast:responseObject[@"msg"]];
                        }
                    }
                    failure:^(NSError *aError) {
                        
                    }];
                };
            }else if (i==2){
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"选择性别" preferredStyle:UIAlertControllerStyleActionSheet];
                UIAlertAction *manSelect = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    ((UILabel *)[self.view viewWithTag:52]).text = @"男";
                    
                    NSDictionary *param = [NSMutableDictionary dictionary];
                    [param setValue:[XDXShareInstance shareInstance].userId forKey:@"userId"];
                    [param setValue:@"0" forKey:@"sex"];
                    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                    [manager encryptedPUT:@"/system/user/modify"
                    parameters:param
                    success:^(NSDictionary *responseObject) {
                        if ([responseObject[@"code"] integerValue]==200) {
                           
                        }else{
                            [[HCToast shareInstance] showToast:responseObject[@"msg"]];
                        }
                    }
                    failure:^(NSError *aError) {
                        
                    }];
                }];
                [alertController addAction:manSelect];
                
                UIAlertAction *womanSelect = [UIAlertAction actionWithTitle:@"女"style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    ((UILabel *)[self.view viewWithTag:52]).text = @"女";
                    
                    NSDictionary *param = [NSMutableDictionary dictionary];
                    [param setValue:[XDXShareInstance shareInstance].userId forKey:@"userId"];
                    [param setValue:@"1" forKey:@"sex"];
                    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                    [manager encryptedPUT:@"/system/user/modify"
                    parameters:param
                    success:^(NSDictionary *responseObject) {
                        if ([responseObject[@"code"] integerValue]==200) {
                           
                        }else{
                            [[HCToast shareInstance] showToast:responseObject[@"msg"]];
                        }
                    }
                    failure:^(NSError *aError) {
                        
                    }];
                }];
                [alertController addAction:womanSelect];
                
                UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alertController addAction:actionCancel];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }];
    }
    
    UILabel *safe = [[UILabel alloc] initWithFrame:CGRectMake(16, infoView.maxY+16, SCREEN_WIDTH-32, 24)];
    safe.font = REAL_MEDIUM_FONT(14);
    safe.text = @"账号安全";
    safe.textColor = GraryLightColor;
    [self.view addSubview:safe];
    
    NSArray *saveArray = @[@{@"title":@"手机号"},@{@"title":@"微信"},@{@"title":@"Apple ID"}];
    
    UIView *saveView = [[UIView alloc] initWithFrame:CGRectMake(16, safe.maxY+8, SCREEN_WIDTH-32, 144)];
    saveView.backgroundColor = RealWhiteColor;
    saveView.layer.masksToBounds = YES;
    [saveView.layer setCornerRadius:16];
    [self.view addSubview:saveView];
    
    for (int i = 0; i < saveArray.count; i ++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, i*48, infoView.width, 48)];
        [saveView addSubview:button];
        
        
        UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(16, button.maxY, infoView.width-32, 1)];
        line.image = [UIImage imageNamed:@"line"];
        [saveView addSubview:line];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, 66, button.height)];
        label.textColor = RealBlackColor;
        label.font = MEDIUM_FONT(15);
        label.text = saveArray[i][@"title"];
        [button addSubview:label];
        
        UILabel *subLabel = [[UILabel alloc] initWithFrame:CGRectMake(infoView.width-186, 0, 150, button.height)];
        subLabel.textColor = GraryTooHeavyColor;
        subLabel.font = DEFAULT_FONT(14);
        subLabel.textAlignment = NSTextAlignmentRight;
        subLabel.tag = 100+i;
        [button addSubview:subLabel];
        
        UIImageView *arrow = [[UIImageView alloc] initWithFrame:CGRectMake(button.width-28, (button.height-12)/2, 12, 12)];
        arrow.image = [UIImage imageNamed:@"arrow_right"];
        [button addSubview:arrow];
        [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if (i==0) {
                if ([subLabel.text isEqualToString:@"未绑定"]) {
                    BlingPhoneView *view = [[BlingPhoneView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) IsChangePhone:NO];
                    [self.view addSubview:view];
                    view.BlingPhoneSuccessBlock = ^(NSString *phone) {
                        subLabel.text = phone;
                    };
                }else{
                    BlingPhoneView *view = [[BlingPhoneView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) IsChangePhone:YES];
                    [self.view addSubview:view];
                    view.BlingPhoneSuccessBlock = ^(NSString *phone) {
                        subLabel.text = phone;
                    };
                }
            }else if (i==1){
                if ([subLabel.text isEqualToString:@"未绑定"] && [WXApi isWXAppInstalled]) {
                    SendAuthReq *req = [[SendAuthReq alloc] init];
                    req.state = @"wx_oauth_authorization_state";
                    req.scope = @"snsapi_userinfo";
                    [WXApi sendReq:req completion:nil];
                }
                
            }else if (i==2){
                if ([subLabel.text isEqualToString:@"未绑定"]) {
                    if (@available(iOS 13.0, *)) {
                        ASAuthorizationAppleIDProvider * appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
                        ASAuthorizationAppleIDRequest * authAppleIDRequest = [appleIDProvider createRequest];
                        authAppleIDRequest.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
                        NSMutableArray <ASAuthorizationRequest *> * array = [NSMutableArray arrayWithCapacity:1];
                        if (authAppleIDRequest) {
                            [array addObject:authAppleIDRequest];
                        }
                        
                        NSArray <ASAuthorizationRequest *> * requests = [array copy];
                        ASAuthorizationController * authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:requests];
                        authorizationController.delegate = self;
                        [authorizationController performRequests];
                    }
                }
            }
        }];
    }
    
    UILabel *delete = [[UILabel alloc] initWithFrame:CGRectMake(16, saveView.maxY+16, SCREEN_WIDTH-32, 24)];
    delete.font = REAL_MEDIUM_FONT(14);
    delete.text = @"注销";
    delete.textColor = GraryLightColor;
    [self.view addSubview:delete];
    
    UIButton *deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(16, delete.maxY+8, SCREEN_WIDTH-32, 48)];
    deleteButton.backgroundColor = RealWhiteColor;
    deleteButton.layer.masksToBounds = YES;
    [deleteButton.layer setCornerRadius:16];
    [self.view addSubview:deleteButton];
    [[deleteButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        AccountLogoutView *view = [[AccountLogoutView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        [self.view addSubview:view];
        view.AccountLogoutBlock = ^{
            [[XDXSocket shareInstance] close];
            
            [XDXShareInstance shareInstance].userId = @"";
            [XDXShareInstance shareInstance].nickName = @"";
            [XDXShareInstance shareInstance].access_token = @"";
            [XDXShareInstance shareInstance].xg_token = @"";
            
            [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:UserId];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:AccessToken];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:NickName];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:Avatar];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:ShowTraffic];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:RoadNet];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:MapType];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:GroupId];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:GroupListTime];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:LastRegionSendTime];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[XDXLocationManager shareInstance].locationManager stopUpdatingHeading];
            [[XDXLocationManager shareInstance].locationManager stopUpdatingLocation];
            [[XDXLocationManager shareInstance].locationManager stopMonitoringSignificantLocationChanges];
            [[XDXLocationManager shareInstance].locationManager stopMonitoringVisits];
            
            {
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *documentsDirectory = [paths objectAtIndex:0];
                NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"GroupList.plist"];
                // 删除plist文件
                NSFileManager *fileManager = [NSFileManager defaultManager];
                if ([fileManager fileExistsAtPath:plistPath]) {
                    [fileManager removeItemAtPath:plistPath error:nil];
                }
            }
            {
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *documentsDirectory = [paths objectAtIndex:0];
                NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"Regions.plist"];
                // 删除plist文件
                NSFileManager *fileManager = [NSFileManager defaultManager];
                if ([fileManager fileExistsAtPath:plistPath]) {
                    [fileManager removeItemAtPath:plistPath error:nil];
                }
            }
            {
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *documentsDirectory = [paths objectAtIndex:0];
                NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"driveLog.plist"];
                // 删除plist文件
                NSFileManager *fileManager = [NSFileManager defaultManager];
                if ([fileManager fileExistsAtPath:plistPath]) {
                    [fileManager removeItemAtPath:plistPath error:nil];
                }
            }
            {
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *documentsDirectory = [paths objectAtIndex:0];
                NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"regionLog.plist"];
                // 删除plist文件
                NSFileManager *fileManager = [NSFileManager defaultManager];
                if ([fileManager fileExistsAtPath:plistPath]) {
                    [fileManager removeItemAtPath:plistPath error:nil];
                }
            }
            
            LoginViewController *vc = [[LoginViewController alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
            [UIApplication sharedApplication].keyWindow.rootViewController = nav;
            [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
        };
    }];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, 66, deleteButton.height)];
    label.textColor = RedColor;
    label.font = REAL_MEDIUM_FONT(15);
    label.text = @"注销账号";
    [deleteButton addSubview:label];
    
    UIImageView *arrow = [[UIImageView alloc] initWithFrame:CGRectMake(deleteButton.width-30, (deleteButton.height-12)/2, 12, 12)];
    arrow.image = [UIImage imageNamed:@"arrow_right"];
    [deleteButton addSubview:arrow];
}

- (void)getUserInfo
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
    [manager encryptedPOST:@"/system/user/getInfo"
    parameters:param
    success:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue]==200 ) {
            [self.head sd_setImageWithURL:[NSURL URLWithString:responseObject[@"data"][@"avatar"]]];
            if ([responseObject[@"data"][@"nickName"] isKindOfClass:[NSString class]] && [responseObject[@"data"][@"nickName"] length]>0) {
                ((UILabel *)[self.view viewWithTag:51]).text = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"nickName"]];
            }
            if ([responseObject[@"data"][@"sex"] integerValue]==0) {
                ((UILabel *)[self.view viewWithTag:52]).text = @"男";
            }else{
                ((UILabel *)[self.view viewWithTag:52]).text = @"女";
            }
            
            if ([responseObject[@"data"][@"phonenumber"] isKindOfClass:[NSString class]] && [responseObject[@"data"][@"phonenumber"] length]>0) {
                ((UILabel *)[self.view viewWithTag:100]).text = [NSString stringWithFormat:@"+86 %@",responseObject[@"data"][@"phonenumber"]];
            }else{
                ((UILabel *)[self.view viewWithTag:100]).text = @"未绑定";
            }
            if ([[responseObject[@"data"][@"thirdPartLogin"] firstObject][@"wechatOpenId"] isKindOfClass:[NSString class]] && [[responseObject[@"data"][@"thirdPartLogin"] firstObject][@"wechatOpenId"] length]>0) {
                if ([[responseObject[@"data"][@"thirdPartLogin"] firstObject][@"wechatNickName"] isKindOfClass:[NSString class]] && [[responseObject[@"data"][@"thirdPartLogin"] firstObject][@"wechatNickName"] length]>0) {
                    ((UILabel *)[self.view viewWithTag:101]).text = [NSString stringWithFormat:@"%@",[responseObject[@"data"][@"thirdPartLogin"] firstObject][@"wechatNickName"]];
                }else{
                    ((UILabel *)[self.view viewWithTag:101]).text = @"已绑定";
                }
            }else{
                ((UILabel *)[self.view viewWithTag:101]).text = @"未绑定";
            }
            
            if ([[responseObject[@"data"][@"thirdPartLogin"] lastObject][@"appleOpenId"] isKindOfClass:[NSString class]] && [[responseObject[@"data"][@"thirdPartLogin"] lastObject][@"appleOpenId"] length]>0) {
                if ([[responseObject[@"data"][@"thirdPartLogin"] firstObject][@"appleNickName"] isKindOfClass:[NSString class]] && [[responseObject[@"data"][@"thirdPartLogin"] firstObject][@"appleNickName"] length]>0) {
                    ((UILabel *)[self.view viewWithTag:102]).text = [NSString stringWithFormat:@"%@",[responseObject[@"data"][@"thirdPartLogin"] firstObject][@"wechatNickName"]];
                }else{
                    ((UILabel *)[self.view viewWithTag:102]).text = @"已绑定";
                }
            }else{
                ((UILabel *)[self.view viewWithTag:102]).text = @"未绑定";
            }
        }
    }
    failure:^(NSError *aError) {
        
    }];
}

- (void)album
{
    UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    [controller setDelegate:self];
    if ([controller isAvailablePhotoLibrary]) {
        [self presentViewController:controller animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [self dismissViewControllerAnimated:YES completion:^{
        UIImage *imageOriginal = [info objectForKey:UIImagePickerControllerOriginalImage];
        HQImageEditViewController *vc = [[HQImageEditViewController alloc] init];
        vc.originImage = [self fixOrientationWithImage:imageOriginal];
        vc.delegate = self;
        vc.maskViewAnimation = YES;
        [self presentViewController:vc animated:YES completion:nil];
    }];
}

- (UIImage *)fixOrientationWithImage:(UIImage *)image
{

    // No-op if the orientation is already correct
    if (image.imageOrientation == UIImageOrientationUp) return image;

    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;

    switch (image.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, image.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;

        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;

        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, image.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
    }

    switch (image.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;

        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
    }

    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, image.size.width, image.size.height,
                                             CGImageGetBitsPerComponent(image.CGImage), 0,
                                             CGImageGetColorSpace(image.CGImage),
                                             CGImageGetBitmapInfo(image.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (image.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,image.size.height,image.size.width), image.CGImage);
            break;

        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,image.size.width,image.size.height), image.CGImage);
            break;
    }

    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

- (void)saveImage:(UIImage *)image
{
    UIImage *saveImage = [self compressImage:image toSize:CGSizeMake(200, 200)];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent: [NSString stringWithFormat:@"avatarfile.png"]];
    BOOL result = [UIImagePNGRepresentation(saveImage) writeToFile:filePath atomically:YES];
    if (result == YES) {
        NSLog(@"保存成功");
        self.head.image = saveImage;
        [self uploadWithUrl:[NSURL fileURLWithPath:filePath]];
    }
}

- (UIImage *)compressImage:(UIImage *)image toSize:(CGSize)size
{
  UIGraphicsBeginImageContext(size);
  [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
  UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return scaledImage;
}


- (void)editController:(HQImageEditViewController *)vc finishiEditShotImage:(UIImage *)image originSizeImage:(UIImage *)originSizeImage
{
    [self saveImage:originSizeImage];
    [vc dismissViewControllerAnimated:YES completion:nil];
}

- (void)editControllerDidClickCancel:(HQImageEditViewController *)vc
{
    [vc dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadWithUrl:(NSURL *)url
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
    [manager POST:[NSString stringWithFormat:@"%@/system/user/profile/avatar",NETURL] parameters:nil headers:@{@"Authorization":[XDXShareInstance shareInstance].access_token} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
      
        NSData *fileData = [NSData dataWithContentsOfURL:url];
        [formData appendPartWithFileData:fileData name:@"avatarfile" fileName:[[NSString stringWithFormat:@"%@",[XDXShareInstance shareInstance].userId] stringByAppendingString:@".png"] mimeType:@"png"];

    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark- ASAuthorizationControllerDelegate
// 授权成功
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization
API_AVAILABLE(ios(13.0))
{
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        ASAuthorizationAppleIDCredential *credential = (ASAuthorizationAppleIDCredential *)authorization.credential;     
        NSString *authorizationCodeString = credential.authorizationCode ? [[NSString alloc] initWithData:credential.authorizationCode encoding:NSUTF8StringEncoding] : @"";

        NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
        [param setValue:authorizationCodeString forKey:@"authorizationCode"]; // 服务端换取 token
        CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
        [manager encryptedPOST:@"/auth/bindapple"
        parameters:param
        success:^(NSDictionary *responseObject) {
            if ([responseObject[@"code"] integerValue]==200) {
                [self getUserInfo];
            }else{
                [[HCToast shareInstance] showToast:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
            }
        }
        failure:^(NSError *aError) {
           
        }];
    }
}
// 授权失败
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error
API_AVAILABLE(ios(13.0)){
    
}

- (void)WXBling:(NSNotification *)notify
{
    NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
    [param setValue:notify.userInfo[@"code"] forKey:@"code"];
    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
    [manager encryptedPOST:@"/auth/bindwechat"
    parameters:param
    success:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue]==200) {
            [self getUserInfo];
        }else{
            [[HCToast shareInstance] showToast:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
        }
    }
    failure:^(NSError *aError) {
        
    }];
}

@end
